package com.homework.note.Service.impl;

import ch.qos.logback.core.util.FileUtil;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.homework.note.Model.Enum.StatusType;
import com.homework.note.Model.Enum.TrashType;
import com.homework.note.Model.Note;
import com.homework.note.Model.Trash;
import com.homework.note.Repository.NoteRepository;
import com.homework.note.Repository.TrashRepository;
import com.homework.note.Service.NoteService;
import com.homework.note.Util.AuthUtil;
import com.homework.note.Util.ExportUtil;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.util.Assert;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xjx
 * @date 2019/3/10
 */
@Service
public class NoteServiceImpl implements NoteService {

    @Autowired
    NoteRepository noteRepository;

    @Autowired
    TrashRepository trashRepository;

    @Autowired
    private GridFsTemplate gridFsTemplate;


    /**
     * 增
     *
     * @param fatherID
     * @return
     * @throws Throwable
     */
    @Override
    public Note createNote(String fatherID) throws Throwable {
        String user_id = AuthUtil.getUserId();
        Note note = new Note();
        note.setUserID(user_id);
        note.setTitle("无标题笔记");
        note.setContent("");
        note.setStatus(StatusType.Normal);
        note.setCreateTime(new Date());
        note.setModTime(new Date());
        noteRepository.save(note);
        return note;
    }

    /**
     * 查
     *
     * @return
     */
    @Override
    public List<Note> getNoteList() {
        return noteRepository.findAll();
    }

    /**
     * 删
     *
     * @param id
     * @return
     */
    @Override
    public String deleteNote(String id) {
        Note note = noteRepository.findById(id).get();
        Trash trash = new Trash();
        trash.setDocumentID(note.getId());
        trash.setType(TrashType.File);
        trash.setDeleteTime(new Date());
        trashRepository.save(trash);
        note.setStatus(StatusType.Delete);
        noteRepository.save(note);
        return "笔记删除成功";

    }

    /**
     * 改
     *
     * @param title
     * @param content
     * @return
     */
    @Override
    public Note updateNote(String noteID, String title, String content, MultipartFile file, HttpServletRequest request) throws IOException {
        Note note = noteRepository.findById(noteID).orElseThrow(() -> new RuntimeException("该笔记不存在"));
        note.setTitle(title);
        note.setContent(content);
        note.setModTime(new Date());
        //gridfs上传图片完成，输出功能待开发
//        String filename = file.getOriginalFilename();//获取文件名
//        InputStream ins = file.getInputStream();//获取输入流
//        ObjectId objectId = gridFsTemplate.store(ins, filename);
//        note.setPicUrl(objectId.toString());
        //存路径法如下
        //String path = "com/homework/note/Picture/";
        String path = request.getSession().getServletContext().getRealPath("/");
        try {
            file.transferTo(new File(path + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        note.setPicUrl(path + file.getOriginalFilename());

        noteRepository.save(note);
        return note;
    }

    //图片显示功能，有问题，未完成
    @Override
    public GridFSFile getById(ObjectId objectId) {
        return gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(objectId)));
    }

    @Override
    public String export2word(String noteID, HttpServletRequest request, HttpServletResponse response) {
        Note note = noteRepository.findById(noteID).orElseThrow(() -> new RuntimeException("该笔记不存在"));
        Map<String,Object> params = new HashMap<>();
        params.put("title",note.getTitle());
        params.put("content",note.getContent());
        ExportUtil.exportWord("word/export.docx", "E:/test", "aaa.docx", params , request, response);
        return "导出成功";
    }


}
